public class Solution2 {
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists.length == 0 || (lists.length == 1 && lists[0] == null)) return null;
        return mergeSort(lists, 0, lists.length - 1);
    }
    private ListNode mergeSort(ListNode[] lists, int left, int right){
        if(left >= right) return lists[left];
        int mid = (left + right) / 2;
        ListNode head1 = mergeSort(lists, left, mid);
        ListNode head2 = mergeSort(lists, mid + 1, right);
        ListNode cur1 = head1;
        ListNode cur2 = head2;
        ListNode head = new ListNode();
        ListNode cur = head;
        while(cur1 != null && cur2 != null){
            if(cur1.val < cur2.val){
                cur.next = cur1;
                cur1 = cur1.next;
            }else{
                cur.next = cur2;
                cur2 = cur2.next;
            }
            cur = cur.next;
        }
        if(cur1 != null){
            cur.next = cur1;
        }else if(cur2 != null){
            cur.next = cur2;
        }
        return head.next;
    }
}
